package net.vsame.url2sql.web;

import java.lang.reflect.Method;
import java.util.List;

import net.vsame.url2sql.domain.InterceptorConfig;
import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.domain.UrlConfig;
import net.vsame.url2sql.helper.JsHelper;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.web.bigpipe.BigpipeDataHelper;

public class Url2SqlCore {

	public static void handel() {
		Url2SqlContext context = WebHelper.getContext();
		UrlConfig urlConfig = context.getUrlConfig();
		String url = context.getUrl();
		//执行拦截器
		List<InterceptorConfig> interceptors = UrlSqlMappingHelper.getInterceptorConfigs();
		for(InterceptorConfig c : interceptors){
			if(c.getRegex()!=null && url.matches(c.getRegex())){
				JsHelper.execute(c.getJs());
				if(BigpipeDataHelper.hasError()){
					//拦截
					return ;
				}
			}
		}
		//TODO 数据校验
		
		
		//执行Sql或JS
		if(urlConfig.getClazz()!=null){
			invoke(urlConfig.getClazz(), urlConfig.getMethod());
			return ;	
		}else if(urlConfig.getJs()!=null && !"".equals(urlConfig.getJs())){
			//执行JS
			JsHelper.execute(urlConfig.getJs());
		}else if(urlConfig.getSql()!=null && !"".equals(urlConfig.getSql())){
			//执行Sql
			Object o = SqlHelper.execute(urlConfig.getSql(), WebHelper.getContext().getParams());
			BigpipeDataHelper.putUsefulData("data", o);
		}
		
	}

	/**
	 * 执行Java代码
	 * @param className
	 * @param methodName
	 */
	private static void invoke(String className, String methodName){
		Class<?> clazz = null;
		try {
			clazz = Class.forName(className);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		if (clazz == null) {
			throw new RuntimeException("no class defined:" + className);
		}
		Method method = null;
		try {
			method = clazz.getMethod(methodName);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		if (method == null) {
			throw new RuntimeException("no method ["+methodName+"] defined in " + className);
		}
		try {
			Object o = clazz.newInstance();
			method.invoke(o);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
